package com.ys.可变字符串;

/**
 * 描述: StringBuffer
 *
 * @author CodeYang
 * @version 2020/12/22 10:13
 */
public class String拼接的效率比较 {
    public static void main(String[] args) {
        // 1字符串比较效率
        stringBuilderAppend();
        stringBufferAppend();
        stringAppend();

    }
    /**
     * stringBuilder 拼接5万次 耗时操作
     */
    static void stringAppend() {
        long start = System.currentTimeMillis();

        String str = "";
        for (int i = 0; i < 50000; i++) {
            str+=i;
        }
        long edn = System.currentTimeMillis();
        System.out.println("StringBuilder:耗时:" + (edn - start));
    }

    /**
     * stringBuilder 拼接5万次 耗时操作
     */
    static void stringBuilderAppend() {
        long start = System.currentTimeMillis();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 50000; i++) {
            sb.append(i);
        }
        long edn = System.currentTimeMillis();
        System.out.println("StringBuilder:耗时:" + (edn - start));
    }

    /**
     * stringBuffer 拼接5万次 耗时操作
     */
    static void stringBufferAppend() {
        long start = System.currentTimeMillis();

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 50000; i++) {
            stringBuffer.append(i);
        }
        long edn = System.currentTimeMillis();
        System.out.println("stringBuffer:耗时:" + (edn - start));
    }
}
